package com.crane.app.web.advice;


import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.utils.BaseContextHandler;
import com.crane.common.framework.constant.AppSessionConstant;
import com.crane.common.framework.jwt.JwtUserToken;
import com.crane.common.framework.jwt.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author bealon
 */
@Aspect
@Component
@Slf4j
public class SessionAspect {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Before(value = "@annotation(com.crane.common.framework.annotation.SessionVerification)")
    public void doBefore(JoinPoint joinPoint) {
        log.info("目标方法名为:" + joinPoint.getSignature().getName());
        Long userId = BaseContextHandler.getUserId();
        if (null == userId) {
            throw new AppException(BasicErrorCode.SESSION_TIMEOUT);
        }
        Object tokenObj = redisTemplate.opsForValue().get(AppSessionConstant.REDIS_SESSION_PREFIX + userId);
        if (null == tokenObj) {
            throw new AppException(BasicErrorCode.SESSION_TIMEOUT);
        }
        JwtUserToken jwtUser = JwtUtil.getInfoFromToken(tokenObj.toString(), JwtUserToken.class).getUserInfo();
        if (!jwtUser.getRandomKey().equals(BaseContextHandler.getRandomKey())) {
            throw new AppException(BasicErrorCode.SESSION_TIMEOUT);
        }
    }
}
